import React, { useEffect, useState, useImperativeHandle, forwardRef } from 'react';
import Router, { withRouter } from '@/router/renderRouter';
import { Tabs, Card, Button, Table, message, Popconfirm, Divider, Tag } from "antd";
import BreadcrumbBox from "@/components/Base/BreadcrumbBox";
import { deepclone, useSyncCallback } from '@/utils'


import { 
  listRole, 
  delRole,
  updateStatus,
  page,
  deleteById,
  findSubByRoleId,
} from '@/api/role'

let milCToken={}
const List = forwardRef((props, ref) => {
  const [activeKey, setActiveKey] = useState('1');
  const [dataSource, setDataSource] = useState([]);
  const [loading, setLoading] = useState(false)
  const [roleName, setRoleName] = useState('')
  const [roleId, setRoleId] = useState('')
  
  // 等state改变后再执行
  const searchData = useSyncCallback(() => {
    handleFinish()
  })
  // 搜索
  const onFinish = () => {
    searchData()
  }
  const handleFinish = async () => {
    try {
      setLoading(true)
      let res;
      if(roleId){
        res = await findSubByRoleId({
          roleId
        })
      }else{
        res= activeKey === '1' ? await listRole() : await page({
          currentPage:1,
          pageSize: 999
        });
      }
      if(res.code === 0) {
        if(roleId){
            setDataSource(res.data || [])
        }else{
          if(activeKey === '1'){
            setDataSource(res.data || [])
          }else{
            setDataSource(res.data.records || [])}
          }
        }
      setLoading(false)
    } catch(error) {
      console.log(error)
    }
  }
  const updateStatus_ = async (managerUserId, status) => {
    try {
      if (typeof milCToken.source === 'function') {
        milCToken.source('终止请求'); //取消请求
      }
      let res = await updateStatus({ managerUserId, status  }, milCToken)
      if(res.code === 0) {
        message.success('操作成功')
        handleFinish()
      }
    } catch (error) {
      console.log(error)
    }
  }
  // 删除
  const deleteFn = async (data) => {
    try {
      if (typeof milCToken.source === 'function') {
        milCToken.source('终止请求'); //取消请求
      }
      let res;
      if(activeKey === '1'){
        res = await delRole({
          roleId: data.id
        }, milCToken)
      }else{
        res = await deleteById({
          managerUserId: data.managerUserId
        }, milCToken)
      }
      if(res.code === 0) {
        message.success('删除成功')
        handleFinish()
      }
    } catch (error) {
      console.log(error)
    }
  }
  useImperativeHandle(ref, () => ({
    // searchData,
  }))
  // 面包屑
  const breadcrumbList = ['系统设置', '角色管理']
  const columns1 =
  [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      align: 'center',
      width: 60,
      render: (text: any, item: any, index: number) => <>{index + 1}</>,
    },
    {
      title: '角色',
      dataIndex: 'name',
      key: 'name',
      align: 'center',
      render: (text, record, index) => text||'--'
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      align: 'center',
      render: (text, record, index) => text||'--'
    },
    {
      title: '新增日期',
      dataIndex: 'createdTime',
      key: 'createdTime',
      align: 'center',
      render: (text, record, index) => text||'--'
    },
    {
      title: '账号',
      dataIndex: 'userAmount',
      key: 'userAmount',
      align: 'center',
      render: (text, record, index) => {
        return <>
          {
            <a onClick={() => {
              setRoleId(record.id)
              setRoleName(record.name)
              setDataSource([])
              setActiveKey('2')
              onFinish()
            }}
            >
              {text}
            </a>
          }
        </>
      }
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      width: 120,
      fixed: 'right',
      render: (text: string, record: any) => {
        return <>
          <a onClick={()=>{
            props.setPageType("roleEdit")
            props.setParams({
              id: record.id,
              name: record.name,
              remark: record.remark,
            })}
          }
          >编辑</a>
          <Divider type="vertical" />
          <Popconfirm
              title="确定删除？"
              onConfirm={() => {
                deleteFn(record)
              }}
              okText="确定"
              cancelText="取消"
            >
              <a>删除</a>
            </Popconfirm>
        </>;
      },
    }
  ];
  const columns2 =
  [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      align: 'center',
      width: 60,
      render: (text: any, item: any, index: number) => <>{index + 1}</>,
    },
    {
      title: '账号',
      dataIndex: 'userName',
      key: 'userName',
      align: 'center',
      render: (text, record, index) => text||'--'
    },
    {
      title: '名称',
      dataIndex: 'nickName',
      key: 'nickName',
      align: 'center',
      render: (text, record, index) => text||'--'
    },
    {
      title: '角色',
      dataIndex: 'roleName',
      key: 'roleName',
      align: 'center',
      render: (text, record, index) => text||'--'
    },
    {
      title: '新增日期',
      dataIndex: 'createdTime',
      key: 'createdTime',
      align: 'center',
      render: (text, record, index) => text||'--'
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      render: (text, row, index) => {
        return <>
          {
            <Tag color={text == 0 ? '#f5222d' : '#52c41a'}
              onClick={() => updateStatus_(row.managerUserId, text == 1 ? 0 : 1)}
            >
              {text == 1 ? '启用' : '停用'}
            </Tag>
          }
        </>
      },
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      width: 120,
      fixed: 'right',
      render: (text: string, record: any) => {
        return <>
          <a onClick={()=>{
            props.setPageType("childAccount")
            props.setParams({
              id: record.managerUserId
            })}
          }
          >编辑</a>
          <Divider type="vertical" />
          <Popconfirm
              title="确定删除？"
              onConfirm={() => {
                deleteFn(record)
              }}
              okText="确定"
              cancelText="取消"
            >
              <a>删除</a>
            </Popconfirm>
        </>;
      },
    }
  ];
  // 首次更新
  useEffect(() => {
    searchData()
    return () => {};
  // eslint-disable-next-line react-hooks/exhaustive-deps
  } , [])
  return (
    <>
      <div className="system-component">
        <BreadcrumbBox list={breadcrumbList}></BreadcrumbBox>
        <div className="system-main">
          <Card>
            <Tabs activeKey={activeKey} onChange={(e)=>{
              setDataSource([])
              setActiveKey(e)
              onFinish()
            }}>
              <Tabs.TabPane tab="角色管理" key="1" />
              <Tabs.TabPane tab="子账号管理" key="2" />
            </Tabs>
            <div style={{marginBottom:'20px'}}>
              {
                roleId
                ?
                activeKey==='2'
                ?
                <div>
                  <span style={{marginRight: '20px'}}>当前角色: {roleName}</span>
                  <Button onClick={()=>{
                    setRoleId('')
                    setRoleName('')
                    setDataSource([])
                    setActiveKey('1')
                    onFinish()
                  }}>返回</Button>
                </div>
                :
                ''
                :
                activeKey==='1'?
                <Button type="primary" onClick={()=>{
                  props.setPageType("roleEdit")
                  props.setParams({
                    id: '',
                    name: '',
                    remark: '',
                  })}
                }>
                  新增角色
                </Button>
                :
                <Button type="primary" onClick={()=>{
                  props.setPageType("childAccount")
                  props.setParams({
                    id: ''
                  })}
                }>
                  新增子账号
                </Button>
              }
            </div>
            <div className='table'>
              <Table 
              loading={loading}
              size='middle'
              bordered
              rowKey={'id'}
              className='antd-table' 
              dataSource={dataSource} 
              columns={(activeKey==='1' && !roleId)?columns1:columns2} />
            </div>
          </Card>
        </div>
      </div>
    </>
  )
})
export default List